<template>
  <div>
    <!-- 面包屑导航栏 start -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item class="index" :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>个人信息</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航栏 end -->

    <!-- 卡片主体区 start -->

    <el-card>
      <el-form ref="UserFormRef" label-width="80px" :model="userInfo" :rules="userRules">
        <el-form-item label="账号" prop="account">
          <el-input v-model.trim="userInfo.account" placeholder="请输入账号" clearable></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="uname">
          <el-input v-model.trim="userInfo.uname" :readonly="true" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model.trim="userInfo.password" placeholder="请输入密码" show-password clearable></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model.trim="userInfo.phone" placeholder="请输入电话" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="userInfo.email" placeholder="请输入邮箱" clearable></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.trim="userInfo.age" placeholder="请输入年龄" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userInfo.sex">
            <el-radio label="男">男</el-radio>ss
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="会员等级" prop="role" v-show="role">
          <el-input v-model.trim="userInfo.role" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="余额" prop="balance" v-show="role">
          <el-input v-model.trim="userInfo.balance" :readonly="true"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部操作按钮 -->
      <el-row class="btns">
        <el-button class="btn-reset" @click="resetFormInput($event)" size="small">重置</el-button>
        <el-button class="btn-often" @click="updateBalance($event)" size="small" v-show="role">充值</el-button>
        <el-button class="btn-often" type="primary" @click="saveUserMessage($event)" size="small">保存</el-button>
      </el-row>
    </el-card>
    <!-- 卡片主体区 end -->

    <!-- 充值余额弹框 start -->
    <el-dialog title="余额充值" :visible.sync="balanceValue" @close="close()" width="35%">
      <div>
        <!-- 信息展示 start -->
        <p>当前余额：{{ userInfo.balance }}</p>
        <p>当前等级：{{ userInfo.role }}</p>
        <p>友情提示：{{ message }}</p>
        <el-form label-position="left" class="addBalance" :rules="balanceRules" label-width="80px" ref="addForm" :model="money">
          <el-form-item prop="balance" label="充值金额">
            <el-input v-model.trim="money.balance"></el-input>
          </el-form-item>
        </el-form>
        <!-- 信息展示 end -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="btn-reset" @click="cancel($event)" size="small">取消</el-button>
        <el-button class="btn-often" type="primary" @click="save($event)" size="small">确定</el-button>
      </div>
    </el-dialog>
    <!-- 修改角色弹框 end -->
    <!-- 充值余额弹框 end -->
  </div>
</template>

<script>
import btn from '../utils/btn.js'
export default {
  data() {
    // 校验电话11位
    const checkPhone = (rule, val, callback) => {
      const reg = /^1(3|4|5|6|7|8|9)([0-9]{9})$/
      if (!val) {
        return callback(new Error('请输入电话号码！'))
      } else if (!reg.test(val)) {
        return callback(new Error('电话号码不存在！'))
      } else {
        return callback()
      }
    }
    const checkAge = (rule, val, callback) => {
      const reg = /^(0|[1-9]\d{0,2})$/
      if (!val) {
        return callback(new Error('年龄不能为空！'))
      } else if (!reg.test(val)) {
        return callback(new Error('格式不正确！'))
      } else {
        return callback()
      }
    }

    const checkBalance = (rule, val, callback) => {
      const reg = /^([1-9]{1}\d*|0)(\.\d{1,2})?$/
      if (!val) {
        return callback(new Error('金额不能为空！'))
      } else if (!reg.test(val)) {
        return callback(new Error('请输入大于0的数字，最多保留两位小数'))
      } else {
        return callback()
      }
    }
    return {
      userInfo: {},
      //   角色权限
      role: true,
      //   充值的余额
      money: {
        balance: ''
      },
      //   修改金额提交数据
      balance: {
        money: 0,
        role: ''
      },
      //   旧密码
      oldPass: '',
      //   充值余额弹框开关
      balanceValue: false,
      //   充值提示
      message: '',
      balanceRules: {
        balance: [{ validator: checkBalance, required: true, triggger: 'blur' }]
      },
      // 校验规则
      userRules: {
        // 账号不能为空
        account: [
          { required: true, message: '账号不能为空', triggger: 'blur' },
          { min: 2, max: 20, message: '账号在2~20个字符之间', triggger: 'blur' }
        ],
        // 密码不能为空
        password: [
          { required: true, message: '密码不能为空', triggger: 'blur' },
          { min: 5, max: 20, message: '密码在5~20个字符之间', triggger: 'blur' }
        ],
        // 电话不能为空
        phone: [{ validator: checkPhone, required: true, triggger: 'blur' }],
        // 性别不能为空
        sex: [{ required: true, message: '请选择性别', triggger: 'blur' }],
        // 年龄不能为空
        age: [{ validator: checkAge, required: true, triggger: 'blur' }]
      }
    }
  },
  created() {
    this.getUserDetail()
  },
  methods: {
    // 获取信息详情
    async getUserDetail() {
      const user = JSON.parse(window.sessionStorage.getItem('user'))
      //   console.log('user', user)
      if (user.role === '超级管理员' || user.role === '管理员') {
        this.role = false
      }
      const res = await this.$http.get('getUserDetail', {
        params: {
          id: user.id
        }
      })
      //   跟新本地存储的用户信息
      sessionStorage.setItem('user', JSON.stringify(res.data))
      // 获取id

      if (res.data) {
        this.userInfo = res.data
        this.oldPass = this.userInfo.password
        // console.log('用户信息', this.userInfo)
        // 判断角色设置充值信息
        this.userInfo.balance = this.userInfo.balance.toFixed(2)
      } else {
        this.$message.error('接口错误！获取失败！')
      }
    },
    // 重置
    resetFormInput(e) {
      btn.preBtnFocus(e)
      this.getUserDetail()
    },
    // 保存用户信息
    async saveUserMessage(e) {
      btn.preBtnFocus(e)
      const res = await this.$http.post('updateUser', this.userInfo)
      //   console.log('修改结果：', res)
      if (res.data === '修改信息成功！') {
        if (this.oldPass === this.userInfo.password) {
          this.$message.success('修改信息成功！')
        } else {
          this.$message.success('修改信息成功，由于修改的密码，需要重新登录！')
          this.$router.push('login')
          window.sessionStorage.removeItem('user')
        }
      } else {
        this.$message.error('修改信息失败！')
      }
    },
    updateBalance(e) {
      const user = this.userInfo
      if (user.role === '普通会员') {
        const num1 = (66 - user.balance).toFixed(2)
        const num2 = (88 - user.balance).toFixed(2)
        this.message = '尊贵的普通会员，您再充值' + num1 + '元您将成为尊贵的高级会员，充值' + num2 + '元您将成为尊贵的高级会员。'
      } else if (user.role === '高级会员') {
        const num = (88 - user.balance).toFixed(2)
        this.message = '尊贵的高级会员用户，再充值' + num + '元您将成为尊贵的超级级会员。'
      } else if (user.role === '超级会员') {
        this.message = '尊贵的超级会员用户，欢迎您的充值，充值前注意确认金额哦！'
      }
      btn.preBtnFocus(e)
      //   打开弹窗
      this.balanceValue = true
    },
    close() {
      this.$refs.addForm.resetFields()
    },
    cancel(e) {
      btn.preBtnFocus(e)
      this.$refs.addForm.resetFields()
      this.balanceValue = false
    },
    // 金额充值
    save(e) {
      btn.preBtnFocus(e)
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          this.balance.money = parseFloat(this.money.balance) + parseFloat(this.userInfo.balance)
          // console.log('全额：', this.balance.money)
          if (this.balance.money < 66) {
            this.balance.role = '普通会员'
          } else if (this.balance.money >= 66 && this.balance.money < 88) {
            this.balance.role = '高级会员'
          } else if (this.balance.money >= 88) {
            this.balance.role = '超级会员'
          }
          //   console.log('角色', this.balance.role)
          //   console.log('余额', this.balance.money)
          const res = await this.$http.post('updateBalanceOrRole', {
            role: this.balance.role,
            balance: this.balance.money,
            id: this.userInfo.id
          })
          //   关闭弹窗
          this.balanceValue = false
          // 刷新数据
          this.getUserDetail()
          if (res.data === '已修改') {
            this.$message.success('充值成功！')
          }
          //   console.log('res', res)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
// 底部按钮组
.btns {
  display: flex;
  justify-content: flex-end;
}

// 余额表单
.addBalance {
  margin-top: 39px;
}
</style>
